from aip import AipSpeech
import pygame
import azure.cognitiveservices.speech as speechsdk
import os


class BaiduTTS:
    def __init__(self, APP_ID, API_KEY, SECRET_KEY):
        self.APP_ID = APP_ID
        self.API_KEY = API_KEY
        self.SECRET_KEY = SECRET_KEY
        self.client = AipSpeech(self.APP_ID, self.API_KEY, self.SECRET_KEY)

    def text_to_speech_and_play(self, text=""):
        result = self.client.synthesis(text, 'zh', 1, {
            'spd': 5,  # 语速
            'vol': 5,  # 音量大小
            'per': 4  # 发声人 百度丫丫
        })  # 得到音频的二进制文件

        if not isinstance(result, dict):
            with open(os.path.dirname(os.path.abspath(__file__))+"/output_audio.mp3", "wb") as f:
                f.write(result)
        else:
            print("语音合成失败", result)
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__))+'/output_audio.mp3')

    def play_audio_with_pygame(self, audio_file_path):
        pygame.mixer.init()
        pygame.mixer.music.load(audio_file_path)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        pygame.mixer.quit()

    def play_voice_open(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_open.mp3')
    def play_voice_exit(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_exit.mp3')
    def play_voice_ok(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_ok.mp3')
    def play_voice_nomusic(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_nomusic.mp3')
    def play_audio(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/output_audio.mp3')
    def stop_playback(self):
        print('取消了')
        if self.is_playing:
            pygame.mixer.music.stop()
        self.is_playing = False


class AzureTTS:
    def __init__(self, AZURE_API_KEY, AZURE_REGION):
        self.AZURE_API_KEY = AZURE_API_KEY
        self.AZURE_REGION = AZURE_REGION
        self.speech_config = speechsdk.SpeechConfig(subscription=AZURE_API_KEY, region=AZURE_REGION)
        self.audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
        # The language of the voice that speaks.
        self.speech_config.speech_synthesis_voice_name = "zh-CN-XiaoyiNeural"
        self.speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=self.speech_config,
                                                              audio_config=self.audio_config)

    def text_to_speech_and_play(self, text):
        # Get text from the console and synthesize to the default speaker.
        speech_synthesis_result = self.speech_synthesizer.speak_text_async(text).get()

        if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print("Speech synthesized for text [{}]".format(text))
        elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = speech_synthesis_result.cancellation_details
            print("Speech synthesis canceled:{}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                if cancellation_details.error_details:
                    print("Error details :{}".format(cancellation_details.error_details))
                    print("Didy you set the speech resource key and region values?")

    def play_voice_open(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_open.mp3')
    def play_voice_exit(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_exit.mp3')
    def play_voice_ok(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_ok.mp3')
    def play_voice_nomusic(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/audio/audio_nomusic.mp3')
    def play_audio(self):
        self.play_audio_with_pygame(os.path.dirname(os.path.abspath(__file__)) + '/output_audio.mp3')

    def play_audio_with_pygame(self, audio_file_path):
        pygame.mixer.init()
        pygame.mixer.music.load(audio_file_path)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        pygame.mixer.quit()
